//
//  MLAShopFoodsListVC.m
//  MagicLampApp
//
//  Created by Zheng on 2019/4/4.
//  Copyright © 2019 zheng.magic.lamp.app. All rights reserved.
//

#import "MLAShopFoodsListVC.h"
#import "MLAShopFoodListHeaderView.h"
#import "MLAShopFoodLeftCell.h"
#import "MLAShopFoodRightCell.h"
#import "MLAShopFoodLeftModel.h"
#import "MLAShopFoodBottomView.h"
#import "MLAShopFoodCartListModel.h"
#import "MLAShopFoodCartListView.h"
#import "MLAShopFoodCommitOrderVC.h"
#import "MLAEaterBookiingVC.h"
#import "MLAFoodDetailVC.h"

@interface MLAShopFoodsListVC () <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *leftTableView;
@property (nonatomic, strong) UITableView *rightTableView;
@property (nonatomic, strong) MLAShopFoodBottomView *bottomView;
@property (nonatomic, strong) MLAShopFoodCartListView *cartListView;


@property (nonatomic, strong) MLAShopFoodCartListModel *cartModel;

@property (nonatomic, strong) NSMutableArray<MLAShopFoodLeftModel *> *leftModelsArr;
@property (nonatomic, strong) NSMutableArray<MLAShopFoodRightModel *> *rightModelsArr;

@property (nonatomic, assign) NSInteger leftIndex;


@end

@implementation MLAShopFoodsListVC

- (void)viewDidLoad {
    [super viewDidLoad];

    _leftIndex = 0;
    
    [self createView];
    
    [self loadLeftData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    
    if (_rightModelsArr.count > 0) {
        [self loadRightData];
    }
    [self loadCartListData];

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}


- (void)loadLeftData {
    
    NSDictionary *param = @{@"type":@"2",
                            @"shop_id":_model.modelId};
    
    [MLAHttpManage postHostType:MLAHttpHostType_Diancan api:productTypeList params:param success:^(id  _Nonnull response, NSString * _Nonnull msg) {
        self.leftModelsArr = [NSMutableArray array];
        self.leftModelsArr = [MLAShopFoodLeftModel mj_objectArrayWithKeyValuesArray:response[@"lists"]];
        [self.leftTableView reloadData];
        [self loadRightData];
    } failure:^{
        
    }];
}

- (void)loadRightData {
    
    MLAShopFoodLeftModel *model = _leftModelsArr[_leftIndex];
    
    NSDictionary *param = @{@"type":@"2",
                            @"shop_id":_model.modelId,
                            @"product_type":model.modelId
                            };
    
    [MLAHttpManage postHostType:MLAHttpHostType_Diancan api:kProductList params:param success:^(id  _Nonnull response, NSString * _Nonnull msg) {
        self.rightModelsArr = [NSMutableArray array];
        self.rightModelsArr = [MLAShopFoodRightModel mj_objectArrayWithKeyValuesArray:response[@"lists"]];
        [self.rightTableView reloadData];
    } failure:^{
        
    }];
    
    
}

- (void)loadCartListData {
    
    NSDictionary *param = @{@"type":@"2",
                            @"shop_id":_model.modelId};
    
    [MLAHttpManage postHostType:MLAHttpHostType_Diancan api:kCartCartCartList params:param success:^(id  _Nonnull response, NSString * _Nonnull msg) {
        self.cartModel = [MLAShopFoodCartListModel mj_objectWithKeyValues:response];
        self.bottomView.numLbl.text = self.cartModel.count;
        self.bottomView.priceLbl.text = [NSString stringWithFormat:@"%.2f",self.cartModel.total.doubleValue/100.];
        _cartListView.model = self.cartModel;
    } failure:^{
        
    }];
    
    
}


#pragma mark - Subivews

- (UITableView *)getTableView {
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    tableView.backgroundColor = [UIColor whiteColor];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.estimatedSectionFooterHeight = 0.0f;
    tableView.estimatedSectionHeaderHeight = 0.0f;
    tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self.view addSubview:tableView];
    
    if (@available(iOS 11.0, *)) {
        tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }

    return tableView;
}

- (void)createView {
    MLAShopFoodListHeaderView *headerView = [[[NSBundle mainBundle] loadNibNamed:@"MLAShopFoodListHeaderView" owner:self options:nil] lastObject];
    headerView.frame = CGRectMake(0, 0, CX_GetScreenWidth(), CX_GetXScale(190));
    [self.view addSubview:headerView];
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.offset(0);
        make.width.offset(CX_GetScreenWidth());
        make.height.offset(CX_GetXScale(190));
    }];
    
    [headerView.shopImgv sd_setImageWithURL:[NSURL URLWithString:_model.shop_logo]];
    headerView.addressLbl.text = [NSString stringWithFormat:@"位置：%@",_model.address];
    headerView.nameLbl.text = _model.shop_name;
    headerView.priceLbl.text = [NSString stringWithFormat:@"人均%@ ¥",_model.person_average];
    headerView.typeLbl.text = _model.shop_type_name;
    headerView.makeBtn.layer.cornerRadius = 5;
    headerView.makeBtn.layer.masksToBounds = YES;
    headerView.makeBtn.layer.borderWidth = 1;
    headerView.makeBtn.layer.borderColor = [UIColor blackColor].CGColor;
    [headerView.backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [headerView.makeBtn addTarget:self action:@selector(makeBtnAction) forControlEvents:UIControlEventTouchUpInside];
    
    
    _leftTableView = [self getTableView];
    _leftTableView.rowHeight = 30;
    _leftTableView.backgroundColor = CX_GetColorHex(0xF1F2F9, 1);
    _leftTableView.bounces = NO;
    [_leftTableView registerClass:[MLAShopFoodLeftCell class] forCellReuseIdentifier:@"leftCell"];
    [_leftTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(CX_GetXScale(190));
        make.width.mas_equalTo(87);
        make.left.offset(0);
        make.bottom.offset(-60);
    }];
    
    self.rightTableView.bounces = NO;
    
    _bottomView = [[MLAShopFoodBottomView alloc] init];
    [_bottomView.cartBtn addTarget:self action:@selector(carBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView.buyBtn addTarget:self action:@selector(buyBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_bottomView];
    [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.offset(0);
        make.height.offset(60);
    }];
}

- (UITableView *)rightTableView {
    if (!_rightTableView) {
        _rightTableView = [self getTableView];
        _rightTableView.rowHeight = 110;
        _rightTableView.bounces = NO;
        [_rightTableView registerNib:[UINib nibWithNibName:@"MLAShopFoodRightCell" bundle:nil] forCellReuseIdentifier:@"rightCell"];
        [_rightTableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(CX_GetXScale(190));
            make.left.offset(87);
            make.right.offset(0);
            make.bottom.offset(-60);
        }];
    }
    return _rightTableView;
}

- (MLAShopFoodCartListView *)cartListView {
    if (!_cartListView) {
        _cartListView = [[MLAShopFoodCartListView alloc] init];
        [_cartListView.bottomView.cartBtn addTarget:self action:@selector(carBtnAction) forControlEvents:UIControlEventTouchUpInside];
        [_cartListView.closeBtn addTarget:self action:@selector(carBtnAction) forControlEvents:UIControlEventTouchUpInside];
        @weakify(self);
        _cartListView.addClickBlock = ^(MLAShopFoodRightModel * _Nonnull model) {
            @strongify(self);
            [self addCartAction:model];
        };
        
        _cartListView.subClickBlock = ^(MLAShopFoodRightModel * _Nonnull model) {
            @strongify(self);
            [self subCartAction:model];
        };
        
        [_cartListView.bottomView.buyBtn addTarget:self action:@selector(buyBtnAction) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _cartListView;
}

#pragma mark - tableview datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == _leftTableView) {
        return _leftModelsArr.count;
    } else if (tableView == _rightTableView) {
        return _rightModelsArr.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == _leftTableView) {
        MLAShopFoodLeftCell *cell = [tableView dequeueReusableCellWithIdentifier:@"leftCell" forIndexPath:indexPath];
        cell.textLabel.font = CX_GetNormalFont(12);

        if (indexPath.row == 0) {
            [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
        }

        MLAShopFoodLeftModel *model = _leftModelsArr[indexPath.row];
        cell.textLabel.text = model.name;

        return cell;
    } else if (tableView == _rightTableView) {
        MLAShopFoodRightCell *cell = [tableView dequeueReusableCellWithIdentifier:@"rightCell" forIndexPath:indexPath];
        MLAShopFoodRightModel *model = _rightModelsArr[indexPath.row];
        cell.model = model;
        
        @weakify(self);
        cell.addClickBlock = ^(MLAShopFoodRightModel * _Nonnull model) {
            @strongify(self);
            [self addCartAction:model];
        };
        
        cell.subClickBlock = ^(MLAShopFoodRightModel * _Nonnull model) {
            @strongify(self);
            [self subCartAction:model];
        };
        
        return cell;
    }
    
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == _leftTableView) {
        
        [_rightTableView removeFromSuperview];
        _rightTableView = nil;
        self.rightTableView.bounces = NO;

        _leftIndex = indexPath.row;
        [self loadRightData];
    } else if (tableView == _rightTableView) {
        MLAShopFoodRightModel *model = _rightModelsArr[indexPath.row];
        MLAFoodDetailVC *fdVC = [[MLAFoodDetailVC alloc] init];
        fdVC.productId = model.modelId;
        [self.navigationController pushViewController:fdVC animated:YES];
    }
}



#pragma mark - Actions
- (void)makeBtnAction {
#pragma mark 预约
    MLAEaterBookiingVC *bookingVC = [[MLAEaterBookiingVC alloc] init];
    bookingVC.shopId = _model.modelId;
    [self.navigationController pushViewController:bookingVC animated:YES];
}

- (void)addCartAction:(MLAShopFoodRightModel *)model {
#pragma mark 添加购物车
    
    NSDictionary *params = @{
                             @"shop_id":model.shop_id,
                             @"product_id":model.modelId,
                             @"num":@"1",
                             @"type":@"1"
                             };
    
    [MLAHttpManage postHostType:MLAHttpHostType_Diancan api:kCartCartCartAdd params:params success:^(id  _Nonnull response, NSString * _Nonnull msg) {
        [self loadRightData];
        [self loadCartListData];
    } failure:^{
        
    }];

}

- (void)subCartAction:(MLAShopFoodRightModel *)model {
#pragma mark 减少购物车
    
    NSDictionary *params = @{
                             @"shop_id":model.shop_id,
                             @"product_id":model.modelId,
                             @"num":@(model.num.integerValue-1),
                             @"type":@"2"
                             };
    
    [MLAHttpManage postHostType:MLAHttpHostType_Diancan api:kCartCartCartAdd params:params success:^(id  _Nonnull response, NSString * _Nonnull msg) {

        [self loadRightData];
        [self loadCartListData];
    } failure:^{
        
    }];
}

- (void)carBtnAction {
#pragma mark 购物车内容
    
    if (_cartListView) {
        [UIView animateWithDuration:.35 animations:^{
            self.cartListView.alpha = 0;
        } completion:^(BOOL finished) {
            [self.cartListView removeFromSuperview];
            self.cartListView = nil;
        }];
    } else {
        
        [[UIApplication sharedApplication].keyWindow addSubview:self.cartListView];
        _cartListView.model = _cartModel;
        [_cartListView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.offset(0);
        }];

        [UIView animateWithDuration:.35 animations:^{
            self.cartListView.alpha = 1;
        }];
     
    }
    
}



- (void)buyBtnAction {
    
#pragma mark 去结算

    [self.cartListView removeFromSuperview];
    self.cartListView = nil;
    
    if (self.cartModel.count.integerValue == 0) {
        return;
    }
    
    MLAShopFoodCommitOrderVC *sfcoVC = [[MLAShopFoodCommitOrderVC alloc] init];
    sfcoVC.cartModel = self.cartModel;
    sfcoVC.shopName = _model.shop_name;
    sfcoVC.address = _model.address;
    sfcoVC.shopId = _model.modelId;
    [self.navigationController pushViewController:sfcoVC animated:YES];
    
}

@end
